use crate::browser::BrowserManager;
use crate::database::{Account, Database};
use anyhow::{anyhow, Result};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::Mutex;
use uuid::Uuid;
use reqwest;
use serde_json;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct XiaohongshuAccount {
    pub id: String,
    pub username: String,
    pub nickname: String,
    pub phone: String,
    pub status: String,
    pub followers: i32,
    pub following: i32,
    pub posts: i32,
    pub last_login: String,
    pub cookies: Option<String>,
    pub token: Option<String>,
    pub is_current: bool,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LoginResult {
    pub success: bool,
    pub message: String,
    pub account: Option<XiaohongshuAccount>,
    pub cookies: Option<String>,
    pub token: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SyncResult {
    pub success: bool,
    pub message: String,
    pub data: Option<AccountData>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AccountData {
    pub followers: i32,
    pub following: i32,
    pub posts: i32,
    pub last_login: String,
}

pub struct XiaohongshuService {
    pub browser_manager: Arc<Mutex<BrowserManager>>,
    pub database: Arc<Mutex<Database>>,
}

impl XiaohongshuService {
    pub fn new() -> Result<Self> {
        Ok(Self {
            browser_manager: Arc::new(Mutex::new(BrowserManager::new()?)),
            database: Arc::new(Mutex::new(Database::new()?)),
        })
    }

    pub async fn open_login_page(&self) -> Result<()> {
        println!("打开小红书登录页面...");
        
        let mut browser_manager = self.browser_manager.lock().await;
        
        // 确保浏览器已初始化
        if !browser_manager.is_initialized() {
            println!("浏览器未初始化，尝试初始化...");
            match browser_manager.initialize().await {
                Ok(_) => println!("浏览器初始化成功"),
                Err(e) => {
                    println!("浏览器初始化失败: {}, 尝试直接调用HTTP接口", e);
                    // 即使初始化失败，也尝试直接调用HTTP接口
                }
            }
        }
        
        // 打开登录页面
        browser_manager.open_login_page().await?;
        
        println!("登录页面已打开，请手动完成登录");
        Ok(())
    }

    pub async fn check_status(&self) -> Result<bool> {
        println!("开始检查登录状态...");
        
        let mut browser_manager = self.browser_manager.lock().await;
        
        // 如果浏览器未初始化，尝试初始化
        if !browser_manager.is_initialized() {
            println!("浏览器未初始化，尝试初始化...");
            match browser_manager.initialize().await {
                Ok(_) => println!("浏览器初始化成功"),
                Err(e) => {
                    println!("浏览器初始化失败: {}, 尝试直接调用HTTP接口", e);
                    // 即使初始化失败，也尝试直接调用HTTP接口
                }
            }
        }
        
        println!("调用浏览器管理器检查登录状态...");
        let result = browser_manager.check_login_status().await;
        println!("浏览器管理器返回结果: {:?}", result);
        
        result
    }

    pub async fn get_login_info_and_save(&self) -> Result<LoginResult> {
        println!("获取登录信息并保存...");
        
        let browser_manager = self.browser_manager.lock().await;
        let database = self.database.lock().await;
        
        // 检查登录状态
        let is_logged_in = browser_manager.check_login_status().await?;
        
        if !is_logged_in {
            return Ok(LoginResult {
                success: false,
                message: "用户未登录，请先完成登录".to_string(),
                account: None,
                cookies: None,
                token: None,
            });
        }
        
        // 获取登录信息
        let login_info_json = browser_manager.get_login_info().await?;
        let login_info: serde_json::Value = serde_json::from_str(&login_info_json)?;
        
        // 解析cookies
        let cookies = if let Some(cookies_array) = login_info.get("cookies") {
            serde_json::to_string(cookies_array)?
        } else {
            "[]".to_string()
        };
        
        // 生成token
        let token = format!("token_{}", Uuid::new_v4());
        
        // 获取用户信息
        let user_info = login_info.get("userInfo")
            .and_then(|v| v.as_str())
            .unwrap_or("未知用户");
        
        // 获取用户ID
        let user_id = login_info.get("userId")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        
        // 获取用户统计数据
        let user_stats = login_info.get("userStats")
            .and_then(|v| v.as_object())
            .cloned();
        
        // 从统计数据中提取粉丝数、关注数等
        let (followers, following, posts) = if let Some(stats) = &user_stats {
            let followers = stats.get("followers")
                .and_then(|v| v.as_str())
                .and_then(|s| s.parse::<i32>().ok())
                .unwrap_or(0);
            let following = stats.get("following")
                .and_then(|v| v.as_str())
                .and_then(|s| s.parse::<i32>().ok())
                .unwrap_or(0);
            let posts = stats.get("posts")
                .and_then(|v| v.as_str())
                .and_then(|s| s.parse::<i32>().ok())
                .unwrap_or(0);
            (followers, following, posts)
        } else {
            (0, 0, 0)
        };
        
        // 使用用户ID作为手机号标识，如果没有则生成临时ID
        let phone = if !user_id.is_empty() {
            format!("xhs_{}", user_id)
        } else {
            format!("user_{}", Uuid::new_v4().to_string().split('-').next().unwrap_or("unknown"))
        };
        
        // 检查账号是否已存在（这里简化处理，实际应该从登录信息中获取真实手机号）
        let existing_account = database.get_account_by_phone(&phone)?;
        
        let account_id = if let Some(existing) = existing_account {
            // 更新现有账号
            let existing_id = existing.id.clone();
            let updated_account = Account {
                id: existing_id.clone(),
                username: user_info.to_string(),
                nickname: if !user_id.is_empty() { user_info.to_string() } else { format!("用户_{}", phone) },
                phone: phone.clone(),
                status: "active".to_string(),
                followers: followers,
                following: following,
                posts: posts,
                last_login: Some(Utc::now().to_rfc3339()),
                cookies: Some(cookies.clone()),
                token: Some(token.clone()),
                is_current: true,
                created_at: existing.created_at,
                updated_at: Utc::now().to_rfc3339(),
            };
            
            database.update_account(&existing_id, &updated_account)?;
            existing_id
        } else {
            // 创建新账号
            let new_account = Account {
                id: Uuid::new_v4().to_string(),
                username: user_info.to_string(),
                nickname: if !user_id.is_empty() { user_info.to_string() } else { format!("用户_{}", phone) },
                phone: phone.clone(),
                status: "active".to_string(),
                followers: followers,
                following: following,
                posts: posts,
                last_login: Some(Utc::now().to_rfc3339()),
                cookies: Some(cookies.clone()),
                token: Some(token.clone()),
                is_current: true,
                created_at: Utc::now().to_rfc3339(),
                updated_at: Utc::now().to_rfc3339(),
            };
            
            let new_id = new_account.id.clone();
            database.add_account(&new_account)?;
            new_id
        };
        
        // 将其他账号设为非当前账号
        database.set_all_accounts_not_current()?;
        
        // 设置当前账号
        database.set_current_account(&account_id)?;
        
        // 构建返回的账号信息
        let account = XiaohongshuAccount {
            id: account_id,
            username: user_info.to_string(),
            nickname: if !user_id.is_empty() { user_info.to_string() } else { format!("用户_{}", phone) },
            phone: phone,
            status: "active".to_string(),
            followers: followers,
            following: following,
            posts: posts,
            last_login: Utc::now().to_rfc3339(),
            cookies: Some(cookies.clone()),
            token: Some(token.clone()),
            is_current: true,
            created_at: Utc::now().to_rfc3339(),
            updated_at: Utc::now().to_rfc3339(),
        };
        
        println!("登录信息获取并保存成功");
        
        Ok(LoginResult {
            success: true,
            message: "登录信息获取并保存成功".to_string(),
            account: Some(account),
            cookies: Some(cookies),
            token: Some(token),
        })
    }

    pub async fn sync_data(&self, account_id: &str) -> Result<SyncResult> {
        println!("开始同步账号数据...");
        
        let database = self.database.lock().await;
        
        // 获取账号信息
        let account = database.get_account(account_id)?;
        if account.is_none() {
            return Ok(SyncResult {
                success: false,
                message: "账号不存在".to_string(),
                data: None,
            });
        }
        
        // 模拟同步数据（实际应该从小红书API获取）
        let data = AccountData {
            followers: 1250,
            following: 89,
            posts: 45,
            last_login: Utc::now().to_rfc3339(),
        };
        
        println!("数据同步完成");
        
        Ok(SyncResult {
            success: true,
            message: "同步成功".to_string(),
            data: Some(data),
        })
    }

    pub async fn switch_account(&self, account_id: &str) -> Result<()> {
        println!("切换账号: {}", account_id);
        
        let database = self.database.lock().await;
        
        // 将所有账号设为非当前
        database.set_all_accounts_not_current()?;
        
        // 设置指定账号为当前账号
        database.set_current_account(account_id)?;
        
        println!("账号切换成功");
        Ok(())
    }

    pub async fn get_current_account(&self) -> Result<Option<XiaohongshuAccount>> {
        let database = self.database.lock().await;
        let account = database.get_current_account()?;
        
        if let Some(acc) = account {
            let xhs_account = XiaohongshuAccount {
                id: acc.id,
                username: acc.username,
                nickname: acc.nickname,
                phone: acc.phone,
                status: acc.status,
                followers: acc.followers,
                following: acc.following,
                posts: acc.posts,
                last_login: acc.last_login.unwrap_or_default(),
                cookies: acc.cookies,
                token: acc.token,
                is_current: acc.is_current,
                created_at: acc.created_at,
                updated_at: acc.updated_at,
            };
            Ok(Some(xhs_account))
        } else {
            Ok(None)
        }
    }

    pub async fn get_accounts(&self) -> Result<Vec<XiaohongshuAccount>> {
        let database = self.database.lock().await;
        let accounts = database.get_accounts()?;
        
        let xhs_accounts = accounts.into_iter().map(|acc| XiaohongshuAccount {
            id: acc.id,
            username: acc.username,
            nickname: acc.nickname,
            phone: acc.phone,
            status: acc.status,
            followers: acc.followers,
            following: acc.following,
            posts: acc.posts,
            last_login: acc.last_login.unwrap_or_default(),
            cookies: acc.cookies,
            token: acc.token,
            is_current: acc.is_current,
            created_at: acc.created_at,
            updated_at: acc.updated_at,
        }).collect();
        
        Ok(xhs_accounts)
    }

    pub async fn delete_account(&self, account_id: &str) -> Result<()> {
        println!("删除账号: {}", account_id);
        
        let database = self.database.lock().await;
        database.delete_account(account_id)?;
        
        println!("账号删除成功");
        Ok(())
    }

    pub async fn publish(&self, title: &str, content: &str, images: Option<Vec<String>>) -> Result<()> {
        println!("开始发布文章到小红书: 标题={}, 内容长度={}", title, content.len());
        
        let mut browser_manager = self.browser_manager.lock().await;
        
        // 确保浏览器已初始化
        if !browser_manager.is_initialized() {
            println!("浏览器未初始化，尝试初始化...");
            browser_manager.initialize().await?;
        }
        
        // 检查登录状态
        let is_logged_in = browser_manager.check_login_status().await?;
        if !is_logged_in {
            return Err(anyhow!("用户未登录，请先登录小红书账号"));
        }
        
        // 调用Node.js浏览器自动化发布接口
        println!("准备发布内容:");
        println!("标题: {}", title);
        println!("内容: {}", content);
        
        let empty_vec = vec![];
        let image_paths = images.as_ref().unwrap_or(&empty_vec);
        if !image_paths.is_empty() {
            println!("图片数量: {}", image_paths.len());
            for (i, path) in image_paths.iter().enumerate() {
                println!("图片{}: {}", i + 1, path);
            }
        }
        
        // 调用浏览器服务器的发布接口
        let client = reqwest::Client::new();
        let publish_data = serde_json::json!({
            "title": title,
            "content": content,
            "images": images.clone().unwrap_or_default()
        });
        
        println!("调用浏览器自动化发布接口...");
        match client.post("http://localhost:3001/publish")
            .json(&publish_data)
            .send()
            .await {
            Ok(response) => {
                if response.status().is_success() {
                    match response.json::<serde_json::Value>().await {
                        Ok(result) => {
                            if result["success"].as_bool().unwrap_or(false) {
                                println!("小红书自动化发布成功: {}", title);
                                println!("消息: {}", result["message"].as_str().unwrap_or("发布完成"));
                            } else {
                                let error_msg = result["error"].as_str().unwrap_or("未知错误");
                                println!("小红书自动化发布失败: {}", error_msg);
                                return Err(anyhow!("发布失败: {}", error_msg));
                            }
                        },
                        Err(e) => {
                            println!("解析发布响应失败: {}", e);
                            return Err(anyhow!("解析发布响应失败: {}", e));
                        }
                    }
                } else {
                    println!("发布请求失败，状态码: {}", response.status());
                    return Err(anyhow!("发布请求失败，状态码: {}", response.status()));
                }
            },
            Err(e) => {
                println!("无法连接到浏览器服务器: {}", e);
                return Err(anyhow!("无法连接到浏览器服务器: {}", e));
            }
        }
        
        Ok(())
    }
}